#!/bin/bash

# 检查Python脚本是否存在
if [ ! -f "csdn_auto_play.py" ]; then
    echo "错误：未找到csdn_auto_play.py脚本"
    exit 1
fi

# 检查是否存在txt文件
txt_files=$(ls *.txt 2>/dev/null)
if [ -z "$txt_files" ]; then
    echo "错误：当前目录下没有找到任何txt格式的cookie配置文件"
    exit 1
fi

# 获取初始IP地址
initial_ip=$(curl -s ifconfig.me)
echo "============================================"
echo "开始执行自动刷视频任务"
echo "共找到如下cookie文件:$txt_files"
echo "============================================"

# 定义切换IP的函数
switch_ip() {
    local old_ip=$1
    local max_attempts=5  # 最大尝试次数
    local attempt=1
    local new_ip=""
    
    while [ $attempt -le $max_attempts ]; do
        echo -e "\n尝试切换IP (第 $attempt 次)..."
        echo "关开移动数据..."
        adb shell svc data disable
        adb shell svc data enable
        
        # 等待网络重新连接并检查IP变化
        echo "等待网络重新连接并检查IP变化..."
        local wait_attempts=0
        local max_wait_attempts=30  # 最多等待30次，每次1秒
        
        while [ $wait_attempts -lt $max_wait_attempts ]; do
            # 尝试获取新IP
            new_ip=$(curl -s ifconfig.me)
            
            # 检查curl是否成功执行且获取到IP
            if [ $? -eq 0 ] && [ ! -z "$new_ip" ] && [ "$new_ip" != "$old_ip" ]; then
                echo "IP切换成功！"
                echo "旧IP: $old_ip"
                echo "新IP: $new_ip"
                return 0
            fi
            
            wait_attempts=$((wait_attempts + 1))
            sleep 1
        done
        
        echo "IP未发生变化，继续尝试..."
        attempt=$((attempt + 1))
        
        if [ $attempt -gt $max_attempts ]; then
            echo "警告：已达到最大尝试次数($max_attempts)，将继续使用当前IP"
            return 1
        fi
    done
}

# 遍历所有txt文件
for cookie_file in $txt_files; do
    echo -e "\n============================================"
    echo "正在处理cookie文件: $cookie_file"
    
    # 执行Python脚本
    python3 -u csdn_auto_play.py -c "$cookie_file"
    
    # 获取当前IP
    current_ip=$(curl -s ifconfig.me)
    
    # 尝试切换IP
    switch_ip "$current_ip"
    
    echo "============================================"
done

echo -e "\n============================================"
echo "所有账号处理完成"
echo "============================================"
